package com.zxy.fmmall.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxy.fmmall.dao.CategoryMapper;
import com.zxy.fmmall.dao.IndexImgMapper;
import com.zxy.fmmall.entity.Category;
import com.zxy.fmmall.entity.IndexImg;
import com.zxy.fmmall.entity.ProductImg;
import com.zxy.fmmall.service.IndexImgService;
import com.zxy.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class IndexImgServiceImpl implements IndexImgService {
    @Autowired
    private IndexImgMapper indexImgMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public ResultVo listIndexImgs() {
        List<IndexImg> indexImgs = null;


        String imgsStr = stringRedisTemplate.boundValueOps("indexImgs").get();
        try {
            if (imgsStr != null) {
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, IndexImg.class);
                indexImgs = objectMapper.readValue(imgsStr,javaType);
            }else {
                indexImgs = indexImgMapper.listIndexImgs();
                stringRedisTemplate.boundValueOps("indexImgs").set(objectMapper.writeValueAsString(indexImgs),24*60*60);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if (indexImgs.size() != 0) {
            return ResultVo.ok().data("indexImgs", indexImgs);
        } else {
            return ResultVo.error();
        }
    }
}
